package com.skzh.web.controller.history;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.skzh.common.core.domain.model.LoginUser;
import com.skzh.common.utils.SecurityUtils;
import com.skzh.history.utils.KmlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.skzh.common.annotation.Log;
import io.swagger.annotations.ApiOperation;
import com.skzh.common.core.controller.BaseController;
import com.skzh.common.core.domain.AjaxResult;
import com.skzh.common.enums.BusinessType;
import com.skzh.history.domain.TaskHistory;
import com.skzh.history.service.ITaskHistoryService;
import com.skzh.common.utils.poi.ExcelUtil;
import com.skzh.common.core.page.TableDataInfo;

/**
 * 任务执行记录Controller
 *
 * @author skzh
 * @date 2025-04-08
 */
@RestController
@RequestMapping("/history/history")
public class TaskHistoryController extends BaseController {
    @Autowired
    private ITaskHistoryService taskHistoryService;

    /**
     * 查询任务执行记录列表
     */
    @ApiOperation(value = "查询任务执行记录列表")
    @PreAuthorize("@ss.hasPermi('history:history:list')")
    @GetMapping("/list" )
    public TableDataInfo list(TaskHistory taskHistory) {
        startPage();
        List<TaskHistory> list = taskHistoryService.selectTaskHistoryList(taskHistory);
        return getDataTable(list);
    }

    /**
     * 导出任务执行记录列表
     */
    @ApiOperation(value = "导出任务执行记录列表")
    @PreAuthorize("@ss.hasPermi('history:history:export')" )
    @Log(title = "任务执行记录" , businessType = BusinessType.EXPORT)
    @PostMapping("/export" )
    public void export(HttpServletResponse response, TaskHistory taskHistory) {
        List<TaskHistory> list = taskHistoryService.selectTaskHistoryList(taskHistory);
        ExcelUtil<TaskHistory> util = new ExcelUtil<TaskHistory>(TaskHistory. class);
        util.exportExcel(response, list, "任务执行记录数据" );
    }

    /**
     * 获取任务执行记录详细信息
     */
    @ApiOperation(value = "获取任务执行记录详细信息")
    @PreAuthorize("@ss.hasPermi('history:history:query')" )
    @GetMapping(value = "/{recordId}" )
    public AjaxResult getInfo(@PathVariable("recordId" ) Long recordId) {
        return success(taskHistoryService.selectTaskHistoryByRecordId(recordId));
    }

    /**
     * 新增任务执行记录
     */
    @ApiOperation(value = "新增任务执行记录")
    @PreAuthorize("@ss.hasPermi('history:history:add')" )
    @Log(title = "任务执行记录" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TaskHistory taskHistory) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        taskHistory.setCreateBy(loginUser.getUsername());
        return toAjax(taskHistoryService.insertTaskHistory(taskHistory));
    }

    /**
     * 修改任务执行记录
     */
    @ApiOperation(value = "修改任务执行记录")
    @PreAuthorize("@ss.hasPermi('history:history:edit')" )
    @Log(title = "任务执行记录" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TaskHistory taskHistory) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        taskHistory.setUpdateBy(loginUser.getUsername());
        return toAjax(taskHistoryService.updateTaskHistory(taskHistory));
    }

    /**
     * 删除任务执行记录
     */
    @ApiOperation(value = "删除任务执行记录")
    @PreAuthorize("@ss.hasPermi('history:history:remove')" )
    @Log(title = "任务执行记录" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{recordIds}" )
    public AjaxResult remove(@PathVariable Long[] recordIds) {
        return toAjax(taskHistoryService.deleteTaskHistoryByRecordIds(recordIds));
    }


    /**
     * 导出KMZ文件
     */
    @PreAuthorize("@ss.hasPermi('history:history:export')")
    @GetMapping("/exportKmz/{recordId}")
    public void exportKmz(@PathVariable("recordId") Long recordId, HttpServletResponse response) throws IOException {
        TaskHistory taskHistory = taskHistoryService.selectTaskHistoryByRecordId(recordId);
        if (taskHistory == null) {
            throw new RuntimeException("未找到对应的任务记录");
        }

        File kmzFile = KmlUtils.generateKmz(taskHistory);

        try {
            response.setContentType("application/vnd.google-earth.kmz");
            response.setHeader("Content-Disposition", "attachment; filename=" + recordId + ".kmz");

            try (FileInputStream fis = new FileInputStream(kmzFile);
                 OutputStream os = response.getOutputStream()) {

                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }
                os.flush();
            }
        } finally {
            if (kmzFile.exists()) {
                kmzFile.delete();
            }
        }
    }

}
